# -*- coding: utf-8 -*-
# @Time    : 2020/4/7 12:41
# @Author  : duyang
# @Email   : dy2903@126.com
# @File    : main.py
import base64
import json
import uuid
from datetime import datetime
from pathlib import Path

import fire
import pyperclip as pyperclip
import requests
from loguru import logger

LOG = logger

localDate = datetime.now().strftime("%Y/%m/%d")


@LOG.catch
def upload(from_path="D:\config\.my.cnf", to_path=localDate):
	headers = {"Content-Type": "application/json;charset=UTF-8"}
	owner = 'duyang2903'  # str | 用户名(username/login)
	repo = 'res-repo'  # str | 项目路径(path)
	fileName = Path(from_path).name
	path = "{}/{}".format(to_path, fileName)
	# path = '2020/04/07/3.html'  # str | 文件的路径
	message = '自动提交'  # str | 提交信息
	access_token = '3bb7474a8b75a70dec9e8818c125b5ff'  # str | 用户授权码 (optional)
	branch = 'master'  # str | 分支名称。默认为项目对默认分支 (optional)

	content = ""
	with open(from_path, "rb") as f:
		byteContent = f.read()
		content = base64.b64encode(byteContent)

	url = "https://gitee.com/api/v5/repos/{}/{}/contents/{}".format(owner, repo, path)
	formData = {
		'access_token': access_token,
		'content': content,
		"message": message,
		"branch": branch
	}
	try:
		result = requests.post(url, data=formData)
		# LOG.debug("正在请求：{}".format(result.url))
		statusCode = result.status_code

		if "文件名已存在" in result.content.decode("utf-8"):
			LOG.debug("文件已存在，现更新")
			newFileName = "{}{}".format(uuid.uuid1(), Path(fileName).suffix)
			newPath = "{}/{}".format(to_path, newFileName)
			newUrl = "https://gitee.com/api/v5/repos/{}/{}/contents/{}".format(owner, repo, newPath)
			result = requests.post(newUrl, data=formData)
			statusCode = result.status_code

		if statusCode != 201:
			raise Exception("返回的Code 为 {}\n 返回的内容为： {}".format(statusCode, result.content.decode('utf-8')))

		jsonResult = result.json()
		downloadUrl = jsonResult["content"]["download_url"]
		# LOG.info("下载链接: {}".format(downloadUrl))
		pyperclip.copy(downloadUrl)
	except Exception as e:
		raise Exception("请求异常\n\n{}".format(str(e)))


if __name__ == '__main__':
	fire.Fire()
